import MarkdownIt from 'markdown-it';

export function formatMarkdown(text) {
  const md = new MarkdownIt({
    html: true,
    linkify: true,
    typographer: true
  });
  let p = formatMarkdownNew(text)
  return md.render(p);
}



const syntaxRules = {
  javascript: {
    keywords: /\b(function|return|var|let|const|if|else|for|while|do|switch|case|break|continue|try|catch|finally|new|typeof|instanceof|this|class|extends|import|export|default|null|undefined)\b/g,
    strings: /(["'`])(?:(?!\1)[^\\]|\\.)*\1/g,
    comments: /\/\/.*|\/\*[\s\S]*?\*\//g,
    numbers: /\b\d+\.?\d*\b/g,
    functions: /\b\w+(?=\()/g,
  },
  html: {
    tags: /(&lt;\/?)\w+(&gt;)/g,
    attributes: /\s(\w+)=/g,
    strings: /(["'`])(?:(?!\1)[^\\]|\\.)*\1/g,
    comments: /&lt;!--[\s\S]*?--&gt;/g,
  },
  css: {
    properties: /[\w-]+(?=\s*:)/g,
    values: /:\s*(.*?);/g,
    selectors: /[^{}]+(?={)/g,
    comments: /\/\*[\s\S]*?\*\//g,
  }
};
function highlightCode(code, language) {
  // 先进行基本的 HTML 转义，避免 HTML 标签被解析
  code = code.replace(/&/g, '&amp;')
    .replace(/</g, '&lt;')
    .replace(/>/g, '&gt;');

  if (language === 'javascript') {
    // 优化正则匹配，避免产生多余的标记
    const patterns = [
      // 注释
      [/\/\/.*$/gm, 'comment'],
      [/\/\*[\s\S]*?\*\//g, 'comment'],
      // 字符串
      [/(['"`])(?:\\.|(?!\1)[^\\\n])*\1/g, 'string'],
      // 关键字
      [/\b(const|let|var|function|return|if|else|for|while|class|extends)\b/g, 'keyword'],
      // 数字
      [/\b\d+\.?\d*\b/g, 'number'],
      // 函数调用
      [/\b([a-zA-Z_$][a-zA-Z0-9_$]*)\s*\(/g, '$1']
    ];

    // 按顺序应用高亮规则
    patterns.forEach(([regex, className]) => {
      if (className === '$1') {
        code = code.replace(regex, '<span class="code-function">$1</span>(');
      } else {
        code = code.replace(regex, match =>
          `<span class="code-${className}">${match}</span>`
        );
      }
    });
  } else if (language === 'html') {
    code = code.replace(syntaxRules.html.comments, '<span class="code-comment">$&</span>')
      .replace(syntaxRules.html.tags, '<span class="code-keyword">$&</span>')
      .replace(syntaxRules.html.attributes, ' <span class="code-attribute">$1</span>=')
      .replace(syntaxRules.html.strings, '<span class="code-string">$&</span>');
  } else if (language === 'css') {
    code = code.replace(syntaxRules.css.comments, '<span class="code-comment">$&</span>')
      .replace(syntaxRules.css.properties, '<span class="code-property">$&</span>')
      .replace(syntaxRules.css.values, ': <span class="code-value">$1</span>;')
      .replace(syntaxRules.css.selectors, '<span class="code-selector">$&</span>');
  }

  return code;
}
export function formatMarkdownNew(text) {
  if (!text) return '';

  try {
    let html = text
      // 处理代码块
      .replace(/```(\w+)?\n([\s\S]*?)```/g, (match, language, code) => {
        const highlightedCode = highlightCode(code.trim(), language || 'javascript');
        const originalCode = btoa(unescape(encodeURIComponent(code.trim())));

        return `<div class="code-block-wrapper">
          <pre class="code-block">
            <div class="code-header">
              <span>${language || 'javascript'}</span>
              <button class="copy-button" data-code="${originalCode}">复制</button>
            </div>
            <code>${highlightedCode}</code>
          </pre>
        </div>`;
      })
      // 处理行内代码
      .replace(/`([^`]+)`/g, '<code class="inline-code">$1</code>');

    return html;
  } catch (error) {
    console.error('格式化文本时出错:', error);
    return text;
  }
}
